package yatan.common.dao.impl;

import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import yatan.common.dao.DaoException;
import yatan.common.utility.LogUtility;
import yatan.common.utility.ParamUtility;

public abstract class BaseDaoImpl {
    private final Logger logger = Logger.getLogger(getClass());

    private Connection connection;

    public void setConnection(Connection connection) {
        ParamUtility.checkNull(connection, "connection");

        this.connection = connection;
    }

    public void commit() throws DaoException {
        if (connection == null) {
            return;
        }

        try {
            connection.commit();
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                // log and ignore
                LogUtility.logError(this.logger, new DaoException("Cannot rollback transaction. SQL error: "
                        + e.getMessage(), e));
            }
            throw LogUtility.logError(this.logger, new DaoException("Cannot commit to database. SQL error: "
                    + e.getMessage(), e));
        }
    }

    protected Logger getLogger() {
        return this.logger;
    }

    protected Connection getConnection() {
        ParamUtility.checkState(this.connection, "connection");

        return this.connection;
    }

    public void rollback() {
        try {
            this.connection.rollback();
        } catch (SQLException e) {
            this.logger.error("Cannot rollback connection.", e);
        }
    }

    protected void close(ResultSet resultSet, PreparedStatement preparedStatement) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            // ignore
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                // ignore
            }
        }
    }
}
